package mail.util;

import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.han.http.util.Print.printlnInfo;

/**
 * @Author: Hanjiafeng
 * @Date: Created in 15:58 2019/1/22
 * @Desc: 使用正则表达式解析字符串
 */
public class RegexSearcher {

    /**
     * 匹配所有字符串,并将结果放入list中
     *
     * @param inputStr 待匹配字符串
     * @param regexStr 正则字符串
     * @return 匹配结果
     */
    public static LinkedList<String> match(String inputStr, String regexStr) {
        Pattern pattern = Pattern.compile(regexStr);
        Matcher matcher = pattern.matcher(inputStr);
        LinkedList<String> matchedQueue = new LinkedList<>();
        while (matcher.find()) {
            matchedQueue.offer(matcher.group());
        }
        return matchedQueue;
    }

    /**
     * 匹配第一个符合的字符串
     *
     * @param inputStr 待匹配字符串
     * @param regexStr 正则表达式
     * @return 匹配结果
     */
    public static String matchFirst(String inputStr, String regexStr) {

        LinkedList<String> matchedQueue = match(inputStr, regexStr);

        return matchedQueue.isEmpty() ? "" : matchedQueue.poll();
    }

    public static void main(String... args) {
        String m = "https://mail.qq.com/cgi-bin/autoactivation?sid=rMIyUtVzI3QMxGs3&action=reg_activate&actmode=7&tfcont=22%20serialization%3A%3Aarchive%205%200%200%205%200%200%200%208%20authtype%201%204%209%20clientuin%2010%202941749102%206%20domain%206%20qq.com%202%20vm%203%20wpt%202%20ft%209%20loginpage&r=4fa7e48c90b50e566e93a4f14ad5866e";
        String s = RegexSearcher.matchFirst(m, "(?<=/cgi-bin/)((?!\\?).)*(?=\\?)");
        printlnInfo(s);
    }
}
